<template>
<!--  <div class="app-container home">
    <el-row :gutter="20">
      <el-col :sm="24" :lg="12" style="padding-left: 20px">
        <h2>RuoYi-Vue-Plus多租户管理系统</h2>
        <p><b>当前应用ID:</b> <span>{{ sheetId }}</span></p>
      </el-col>
    </el-row>
    <el-divider />
  </div>-->
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search">
        <el-form ref="queryFormRef" v-model="queryParams" :inline="true" label-width="120px">
          <span v-for="(item, index) in searchConfigList">
            <el-form-item :label="item.searchName" :prop="item.searchName" v-if="item.searchType == '1'">
              <el-input :placeholder="item.searchTip" v-model="queryParams.fieldList[index].searchValue" clearable  />
            </el-form-item>
            <el-form-item :label="item.searchName" :prop="item.searchName" v-if="['2', '3'].includes(item.searchType)">
              <el-select clearable filterable v-model="queryParams.fieldList[index].searchValue" :placeholder="item.searchTip" :multiple="item.searchType!='2'">
                <el-option
                  v-for="data in item.dataSourceList"
                  :key="data.value"
                  :label="data.label"
                  :value="data.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="item.searchName" :prop="item.searchName" v-if="['4', '5', '6', '7'].includes(item.searchType)">
              <el-tree-select
                clearable filterable
                v-model="queryParams.fieldList[index].searchValue"
                :multiple="['5', '7'].includes(item.searchType)"
                :placeholder="item.searchTip"
                :data="item.dataSourceList"
                :render-after-expand="false"
                :check-strictly="['6', '7'].includes(item.searchType)"
              />
            </el-form-item>
            <el-form-item :label="item.searchName" :prop="item.searchName" v-if="item.searchType == '8'">
              <el-date-picker
                v-model="queryParams.fieldList[index].searchValue"
                type="date"
                :placeholder="item.searchTip"
              />
            </el-form-item>
            <el-form-item :label="item.searchName" :prop="item.searchName" v-if="item.searchType == '9'">
              <el-date-picker
                v-model="queryParams.fieldList[index].searchValue"
                type="daterange"
                value-format="YYYY-MM-DD"
                :start-placeholder="item.searchTip"
                :end-placeholder="item.searchTip"
              />
            </el-form-item>
          </span>

          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh"  @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">

      <!-- 按钮 -->
      <template #header>
        <el-row :gutter="10" class="mb8">
          <div v-for="item in buttonList">
            <el-col :span="1.5" v-if="item.type == 0 && item.showArea == 1">
              <el-button :type="item.buttonType" plain :icon="item.buttonIcon" @click="buttonClick(item, null)">{{ item.showName }}</el-button>
            </el-col>
            <el-col :span="1.5" v-if="item.type == 1 && item.showArea == 1">
              <el-dropdown class="mt-[1px]">
                <el-button plain>
                  {{ item.showName }}
                  <el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item v-for="child in item.groupList" @click="buttonClick(child, null)" :icon="child.buttonIcon">
                      {{ child.showName }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </el-col>
          </div>

        </el-row>

      </template>

      <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange" max-height="600" border style="width: 100%">
        <el-table-column type="selection" width="55" :cell-style="{ textAlign: 'center' }" />
        <el-table-column
          v-for="(item, index) in tableHeadList"
          :key="index"
          :prop="item.fieldName"
          :label="item.headName"
          :show-overflow-tooltip="true"
          :width="item.tableWidth ? item.tableWidth : ''"
          :cell-style="{ textAlign: 'center' }"
          :fixed="index < sheet?.leftFixedIndex ? 'left' : index >= (tableHeadList.length - sheet?.leftFixedIndex) ? 'right' : null "
        >
          <template #default="scope">
            <div v-if="item.showType != 17">
              {{ scope.row[item.fieldName] }}
            </div>
              <ImagePreview
                v-if="item.showType == 17"
                :width="100"
                :height="100"
                :src="scope.row[item.fieldName]"
                :preview-src-list="[scope.row[item.fieldName]]"
              />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" :cell-style="{ textAlign: 'center' }" class-name="small-padding fixed-width">
          <template #default="scope">
            <span v-for="item in buttonList">
              <el-tooltip :content="item.showName" placement="top" v-if="item.type == 0 && item.showArea == 2">
                <el-button link :type="item.buttonType" :icon="item.buttonIcon" @click="buttonClick(item, scope.row)"></el-button>
              </el-tooltip>

              <el-tooltip :content="item.showName" placement="top" v-if="item.type == 1 && item.showArea == 2">
                <el-dropdown class="mt-[1px]">
                  <el-button link >
                    {{ item.showName }}
                    <el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item v-for="child in item.groupList" @click="buttonClick(child, null)" :icon="child.buttonIcon">
                        {{ child.showName }}
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </el-tooltip>
            </span>

          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
      />
    </el-card>
  </div>
</template>

<script setup name="List" lang="ts">
import { onMounted } from 'vue';
import { useRoute } from 'vue-router'
import { getListData, getSearchAndButtonConfig } from "@/api/sheet/platform/list";
import { RequestParamsDto, SearchButtonDto, SearchConfigDto, SearchFieldDto, TableHead } from "@/api/sheet/platform/list/types";
import { getSheet } from "@/api/sheet/sheet";
import { SheetVO } from "@/api/sheet/sheet/types";
import { clone } from "@/utils/ruoyi";
import { requestDelete } from "@/api/sheet/platform";


const route = useRoute()
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const queryFormRef = ref<ElFormInstance>();
const loading = ref(true);

const total = ref(0);
/** 应用ID */
const sheetId = ref<any>("");
/** 应用信息 */
const sheet = ref<SheetVO>();
/** 查询条件 */
const queryParams = reactive<RequestParamsDto>({
  sheetId: undefined,
  pageNum: undefined,
  pageSize: undefined,
  fieldList: [],
})
/** 按钮列表 */
const buttonList = ref<SearchButtonDto[]>([]);
/** 搜索配置列表 */
const searchConfigList = ref<SearchConfigDto[]>([]);
/** 列表表头 */
const tableHeadList = ref<TableHead[]>([]);
/** 列表数据 */
const dataList = ref([]);
/** 选中ID */
const ids = ref<Array<any>>([]);


/**
 * 获取搜索及按钮配置
 * @param sheetId
 */
const getListSearchAndButtonConfig = async (sheetId: any) => {
  const res = await getSearchAndButtonConfig(sheetId);
  buttonList.value =  res.data.buttonList;
  searchConfigList.value =  res.data.searchConfigList;

  searchConfigList.value.forEach( item => {
    const dto = reactive<SearchFieldDto>({
      fieldId: item.sheetSearchId,
      searchValue: undefined
    })
    queryParams.fieldList?.push(dto)
  })
}

/**
 * 获取列表数据
 * @param queryParams
 */
const getTableData = async (queryParams: any) => {
  const res = await getListData(queryParams);
  console.info(res);
  total.value = res.data.total;
  tableHeadList.value = res.data.headList;
  dataList.value = res.data.dataList;
  loading.value = false;
}

/** 搜索按钮操作 */
const handleQuery = () => {
  if (sheet.value?.isTree == "N"){
    queryParams.pageNum = 1;
  }

  const data = clone(queryParams);
  data.fieldList.forEach(item => {
    if (Array.isArray(item.searchValue)){
      item.searchValue = item.searchValue.join(",");
    }
  })

  getTableData(data);
  console.info(111,queryParams)
}

/** 重置按钮操作 */
const resetQuery = () => {
  console.info(222,queryParams)

  if (sheet.value?.isTree == "N"){
    queryParams.pageNum = 1;
    queryParams.pageSize = 10;
  }
  queryParams.fieldList?.forEach(item => {
    item.searchValue = undefined
  })

  handleQuery();
}

/** 获取应用信息 */
const getSheetMsg = async () => {
  const {data} = await getSheet(sheetId.value);
  sheet.value = data;
  queryParams.sheetId = sheetId.value;
  if (sheet.value.isTree == "N"){
    queryParams.pageNum = 1;
    queryParams.pageSize = 10;
  }
  await getTableData(queryParams);
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item: any) => item[sheet.value?.tableId as string]);
}

/** 按钮点击事件  */
const buttonClick = (item:SearchButtonDto, row:any) => {
  if (item.buttonCode == "add"){
    proxy?.$tab.openPage('/platform/form/index/'+sheetId.value, item.showName+'-'+ sheet.value?.name);
  } else if (item.buttonCode == "edit" || item.buttonCode == "view"){
    let orderId = row[sheet.value?.tableId as string];
    let title = item.buttonCode == "edit" ? item.showName+"-" : item.buttonCode == "view" ? item.showName+"-" : "";
    proxy?.$tab.openPage('/platform/form/index/'+sheetId.value, title + sheet.value?.name, {orderId: orderId});
  } else if (item.buttonCode == "delete"){
    let data = {
      ids: ids.value.join(","),
      sheetId: sheetId.value
    }
    requestDelete(item.apiUrl, data);
    handleQuery();
    proxy?.$modal.msgSuccess("删除成功");
  }
}

onMounted(()=>{
  console.log('id',route.meta.sheetId)
  sheetId.value = route.meta.sheetId;
  getSheetMsg();
  getListSearchAndButtonConfig(sheetId.value);

})

</script>

